package com.ruoyi.hospital.controller.order;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hospital.domain.order.ShopOrdersProduct;
import com.ruoyi.hospital.domain.shop.PharmacyDrugSku;
import com.ruoyi.hospital.domain.vo.StoreGroup;
import com.ruoyi.hospital.service.order.IShopOrdersProductService;
import com.ruoyi.hospital.service.shop.IPharmacyDrugSkuService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.hospital.domain.order.ShopOrders;
import com.ruoyi.hospital.service.order.IShopOrdersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商品订单Controller
 *
 * @author wendao
 * @date 2024-08-19
 */
@RestController
@RequestMapping("/hospital/ProductOrders")
public class ShopOrdersController extends BaseController
{
    @Autowired
    private IShopOrdersService shopOrdersService;
    @Autowired
    private IShopOrdersProductService iShopOrdersProductService;
    @Autowired
    private IPharmacyDrugSkuService iPharmacyDrugSkuService;

    /**
     * 查询商品订单列表
     */
    @PreAuthorize("@ss.hasPermi('hospital:ProductOrders:list')")
    @GetMapping("/list")
    public TableDataInfo list(ShopOrders shopOrders)
    {
        /*用于药店端的查询*/
        if(!StringUtils.isNullOrZero(getStoreId())){
            shopOrders.setStoreId(getStoreId());
        }
        startPage();
        List<ShopOrders> shopOrdersList = shopOrdersService.selectShopOrdersList(shopOrders);
        for(ShopOrders shopOrders1:shopOrdersList){
            shopOrders1.setShopOrdersProductList(iShopOrdersProductService.selectShopOrdersProductListByorderids(shopOrders1.getId(),getStoreId()));
        }

/*

        // 提取所有订单ID
        List<Integer> orderIds = shopOrdersList.stream()
                .map(ShopOrders::getId)
                .collect(Collectors.toList());

        // 批量查询所有订单商品
        List<ShopOrdersProduct> allOrderProducts = iShopOrdersProductService.selectShopOrdersProductListInorderids(orderIds);

        // 按订单ID分组商品
        Map<Integer, List<ShopOrdersProduct>> orderProductsMap = allOrderProducts.stream()
                .collect(Collectors.groupingBy(ShopOrdersProduct::getOrderId));

        // 提取所有SKU ID
        List<Integer> skuIds = allOrderProducts.stream()
                .map(ShopOrdersProduct::getSkuId)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询所有SKU信息
        Map<Integer, PharmacyDrugSku> skuMap;
        if (!skuIds.isEmpty()) {
            List<PharmacyDrugSku> skuList = iPharmacyDrugSkuService.selectPharmacyDrugSkuListInskuIds(skuIds);
            skuMap = skuList.stream()
                    .collect(Collectors.toMap(PharmacyDrugSku::getId, sku -> sku));
        } else {
            skuMap = new HashMap<>();
        }

        // 提取所有店铺ID
        Set<Integer> storeIds = skuMap.values().stream()
                .map(PharmacyDrugSku::getStoreId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 处理每个订单
        for (ShopOrders order : shopOrdersList) {
            List<ShopOrdersProduct> products = orderProductsMap.getOrDefault(order.getId(), Collections.emptyList());
            // 构建SKU列表
            List<PharmacyDrugSku> orderSkuList = products.stream()
                    .map(product -> skuMap.get(product.getSkuId()))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            // 按药店分组
            Map<Integer, List<PharmacyDrugSku>> groupedDrugs = orderSkuList.stream()
                    .collect(Collectors.groupingBy(PharmacyDrugSku::getStoreId));

            List<StoreGroup> storeGroups = groupedDrugs.entrySet().stream()
                    .map(entry -> {
                        Integer storeId = entry.getKey();
                        List<PharmacyDrugSku> drugs = entry.getValue();
                        PharmacyDrugSku firstDrug = drugs.get(0);

                        return new StoreGroup(storeId, firstDrug.getStoreName(), firstDrug.getStoreLogo(), drugs);
                    })
                    .collect(Collectors.toList());

            order.setCollect(storeGroups);
        }*/


        return getDataTable(shopOrdersList);
    }

    /**
     * 导出商品订单列表
     */
    @PreAuthorize("@ss.hasPermi('hospital:ProductOrders:export')")
    @Log(title = "商品订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ShopOrders shopOrders)
    {
        /*用于药店端的查询*/
        if(!StringUtils.isNullOrZero(getStoreId())){
            shopOrders.setStoreId(getStoreId());
        }

        List<ShopOrders> list = shopOrdersService.selectShopOrdersList(shopOrders);
        ExcelUtil<ShopOrders> util = new ExcelUtil<ShopOrders>(ShopOrders.class);
        util.exportExcel(response, list, "商品订单数据");
    }

    /**
     * 获取商品订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('hospital:ProductOrders:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(shopOrdersService.selectShopOrdersById(id));
    }

    /**
     * 新增商品订单
     */
    @PreAuthorize("@ss.hasPermi('hospital:ProductOrders:add')")
    @Log(title = "商品订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ShopOrders shopOrders)
    {
        /*用于药店端的查询*/
        if(!StringUtils.isNullOrZero(getStoreId())){
            shopOrders.setStoreId(getStoreId());
        }

        return toAjax(shopOrdersService.insertShopOrders(shopOrders));
    }

    /**
     * 修改商品订单
     */
    @PreAuthorize("@ss.hasPermi('hospital:ProductOrders:edit')")
    @Log(title = "商品订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ShopOrders shopOrders)
    {
        /*用于药店端的查询*/
        if(!StringUtils.isNullOrZero(getStoreId())){
            shopOrders.setStoreId(getStoreId());
        }

        return toAjax(shopOrdersService.updateShopOrders(shopOrders));
    }

    /**
     * 删除商品订单
     */
    @PreAuthorize("@ss.hasPermi('hospital:ProductOrders:remove')")
    @Log(title = "商品订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(shopOrdersService.deleteShopOrdersByIds(ids));
    }
}
